import eval5, {
  evaluate,
  Function,
  ThrowSyntaxError
} from '../lib/eval5.js'
var showed = false;

//index.js
const app = getApp();
Page({
  data: {
    // 计算部分
    equation: '0',
    isDecimalAdded: false, //判断是否输入小数点，用来防止输入超过一个的小数点
    isOperatorAdded: false, //判断是否点击加减乘除，防止点击超过一次运算符号
    isLeftParenthese: false, //判断是否输入左括号，只能输入一个
    isRightParenthese: false, //判断是否输入右括号，只能输入一个
    isStarted: false, //判断计算器是否开始输入数字，也会用于正负数、百分比计算时作出一些判断
    //控制样式部分
    isSmall: false, //判断结果框的内容过长的时候字符缩小
    isTooSmall: false, //判断更小的时候
    isMessage: false, //控制错误信息的字体大小
    isNightSwitch: false, //控制夜间模式开关
    isMusicSwitch: false, //控制音效开关
    isHistory: false, //控制历史记录的隐藏显示
    isClickCalculate: false,
    //计数器
    count: 0, //计数器，用于计数使用
    //数据部分
    downValue: "︾", //倒三角显示历史记录
    history: [], //编辑录入历史记录
    afterHistory: [], //输出历史记录
    emptyTips: "暂无计算记录", //当无计算记录时显示
    //显示消息
    message: [{
      id: 1,
      error: "主人～，别乱按!🤪"
    }, {
      id: 2,
      error: "请君好好待我!🙂"
    }, {
      id: 3,
      error: "您看清楚再输!🙃"
    }, {
      id: 4,
      error: "🤖机器人：计算出错!"
    }, {
      id: 5,
      error: "我不会算数了!😵"
    }, {
      id: 6,
      error: "体育老师教的！🤐"
    }, {
      id: 7,
      error: "你大错特错了！🙄"
    }, {
      id: 8,
      error: "怪我不够聪明！🤔"
    }, {
      id: 1,
      error: "出错 ⛔️"
    }, {
      id: 1,
      error: "我不蠢，请你别瞎按💢"
    }, ],
  },
  //判断charracter是否为加减乘除
  isOperator: function (character) {
    // console.log(character, "======获取加减乘除");
    // console.log(['+', '-', '×', '÷'].indexOf(character) > -1, "=====获取是哦福位");
    var result = ['+', '-', '×', '÷'].indexOf(character) > -1;
    return result

  },
  append: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/click.mp3";
    }
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    var character = e.currentTarget.dataset.value; //获取当前按键值
    if (this.data.isClickCalculate === true) {
      if (!this.isOperator(character) && character !== '(' && character !== '.') {
        this.data.equation = '0'
      }
      this.data.isClickCalculate = false;
      this.setData({
        isClickCalculate: this.data.isClickCalculate,
        equation: this.data.equation
      })
    }
    // console.log(this.data.equation, this.isOperator(character), this.data.isOperatorAdded, "=====判断当前状态");
    var subtreString = this.data.equation.toString()
    // 判断最后一位是否为加减乘除符号
    if (['+', '-', '×', '÷', '('].indexOf(subtreString.charAt(subtreString.length - 1)) > -1) {
      this.data.isOperatorAdded = true
      this.setData({
        isOperatorAdded: this.data.isOperatorAdded
      })
    } else {
      this.data.isOperatorAdded = false
      this.setData({
        isOperatorAdded: this.data.isOperatorAdded
      })
    }
    // 判断最后一位是否为小数点
    if (subtreString.charAt(subtreString.length - 1) === '.') {
      this.data.isDecimalAdded = true
      this.data.isOperatorAdded = true
      this.setData({
        isDecimalAdded: this.data.isDecimalAdded,
        isOperatorAdded: this.data.isOperatorAdded
      })
    } else {
      // 控制器
      var boolean = true
      // 检索显示框中是否有‘.‘
      for (var i in this.data.equation) {
        if (this.data.equation[i] === '.') {
          boolean = false
        } 
      }
      if (boolean === false) {
        this.data.isDecimalAdded = true
      } else {
        this.data.isDecimalAdded = false
      }
      this.setData({
        isDecimalAdded: this.data.isDecimalAdded,
      })
    }
    if (this.data.equation === '0' && this.isOperator(character) === false) {
      // console.log("进入判断当前值为0与输入值的校验");
      //判断是否输入数字
      if (character === '.') { //判断是否输入小数点
        // console.log(this.data.equation, "=====未加点前");
        this.data.equation += character; //如果输入的是0，则在后面拼接
        // console.log(this.data.equation, "=====加点后");
        this.data.isDecimalAdded = true;
        this.setData({
          equation: this.data.equation,
          isDecimalAdded: this.data.isDecimalAdded,
        });
        // console.log(this.data.equation, "====最后空负值");
      } else {
        // console.log("不为0的时候进入了这里");
        this.data.equation = character; //如果不为0的，直接替换原来数字
        this.setData({
          equation: this.data.equation
        });
        // console.log(this.data.equation, "====最后空负值，不为0的时候进入了这里");
      }
      if (character === ')') {
        //判断如果输入的是 ")",则在输入框中没有内容，需要置为初始化效果
        this.data.equation = "0";
        this.setData({
          equation: this.data.equation
        });
        // console.log(this.data.equation, "====最后空负值，则在输入框中没有内容，需要置为初始化效果");
      }
      //判断输入的是否为括号
      if (character === '(') {
        // 左边括号为真
        this.data.isLeftParenthese = true;
        this.setData({
          isLeftParenthese: this.data.isLeftParenthese
        });
      }

      this.data.isStarted = true;
      this.setData({
        isStarted: this.data.isStarted
      });
      return;
    }
    // 当前不为空时，输入且不为符号
    if (this.isOperator(character) === false) {
      // console.log(this.data.isOperatorAdded, "=====当前乘除加减状态");
      console.log("当前的点:", this.data.isDecimalAdded, "当前输入", character);
      if (character === '.' && this.data.isDecimalAdded) {
        // console.log("进入了这个0");
        //只能输入一个小数点，如果遇到小数点则返回
        return
      } else {
        if (character === '.') { //如果输入小数点
          console.log(this.data.isOperatorAdded, "======判断当前输入为.时的状态");
          if (this.data.isOperatorAdded) {
            // console.log("如果在输入了运算符号的时候，输入小数点会自动加0在前面");
            //如果在输入了运算符号的时候，输入小数点会自动加0在前面
            this.data.equation += '0';
            this.setData({
              equation: this.data.equation
            });
          }
          this.data.isDecimalAdded = true;
          this.data.isOperatorAdded = true;
          this.setData({
            isDecimalAdded: this.data.isDecimalAdded,
            isOperatorAdded: this.data.isOperatorAdded,
          });
        } else {
          this.data.isOperatorAdded = false;
          this.setData({
            isOperatorAdded: this.data.isOperatorAdded
          });
        }
        if (character === ')') {
          // console.log(this.data.equation, this.data.equation.search(/\(/), "=====判断是否存在（");
          // 是否含有左括号
          var isHasLeftParenthese = this.data.equation.search(/\(/) === -1
          if (isHasLeftParenthese) {
            return
          } else {
            var leftNum = 0;
            var rightNum = 0;
            // console.log("含有左括号");
            for (var i in this.data.equation) {
              // console.log(i, "====字符串");
              if (this.data.equation[i] === '(') {
                leftNum++;
              } else if (this.data.equation[i] === ')') {
                rightNum++;
              }
            }
            // console.log(leftNum, rightNum, "======左和右");
            if (leftNum === rightNum) {
              return
            }
          }
        }
        if (character === '(') {
          // console.log(subtreString.charAt(subtreString.length - 1), "=====左括号的最后一位");
          var num = subtreString.charAt(subtreString.length - 1)
          // console.log(num, "=====fsdafsa");
          if (num >= 0 && num <= 9) {
            // console.log("这是对的");
            this.data.equation += '×'
            this.setData({
              equation: this.data.equation
            })
          }
          // console.log(this.data.isDecimalAdded, this.data.isOperatorAdded, "=====判断当前符号状态");
        }
        var res = subtreString.charAt(subtreString.length - 1)
        // console.log(num, "=====fsdafsa");
        if (res === ')') {
          // console.log("这是对的");
          if (character >= 0 && character <= 9) {
            this.data.equation += '×'
            this.setData({
              equation: this.data.equation
            })
          }
        }
      }
      this.data.equation += '' + character; //拼接数字
      this.setData({
        equation: this.data.equation
      });
    }
    if (this.isOperator(character) && !this.data.isOperatorAdded) {
      //当输入运算符号的时候，
      this.data.equation += '' + character;
      this.data.isDecimalAdded = false;
      this.data.isOperatorAdded = true;
      this.setData({
        equation: this.data.equation,
        isOperatorAdded: this.data.isOperatorAdded,
        isDecimalAdded: this.data.isDecimalAdded
      });
    }
    this.showResult();
    // }
  },
  //点击等于符号的时候
  calculate: function (e) {
    var lCom = 0;
    var rCom = 0;
    for (var j in this.data.equation) {
      // console.log(i, "====字符串");
      if (this.data.equation[j] === '(') {
        lCom += 1;
      } else if (this.data.equation[j] === ')') {
        rCom += 1;
      }
    }
    for (var i = 0; i < (lCom - rCom); i++) {
      this.data.equation += ")"
    }
    this.data.emptyTips = ''; //清空历史记录空提醒
    this.setData({
      emptyTips: this.data.emptyTips
    }); //并且立刻数据绑定到界面
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/click.mp3";
    }
    let history = this.data.equation; //历史记录
    let result = this.data.equation.replace(new RegExp('×', 'g'), '*').replace(new RegExp('÷', 'g'), '/'); //替换乘号和除号为程序输入字符
    //try catch获取错误信息，遍历错误的结果
    try {
      this.data.equation = parseFloat(evaluate(result).toFixed(9)).toString(); //计算结果
      var historyMessage = history.toString() + "=" +
        this.data.equation; //把计算记录赋值给历史记录
      this.historyText(historyMessage);
    } catch (err) {
      if (err) {
        var historyMessage = history.toString() + "=错误";
        this.historyText(historyMessage);
        var message = this.data.message; //获取错误信息数组
        //遍历错误信息 数组
        var num = Math.floor(Math.random() * message.length);
        // console.log(num, "=======随机数据");
        this.data.isMessage = true;
        this.data.equation = message[num].error;
        setTimeout(() => {
          this.data.equation = '0';
          this.data.isMessage = false;
          this.setData({
            equation: this.data.equation,
            isMessage: this.data.isMessage,
          });
        }, 2000); //3s后执行清空操作
        // for (var i = 0; i < message.length; i++) {
        //   if (this.data.count === i) {
        //     this.data.isMessage = true;
        //     this.data.equation = message[i].error;
        //     setTimeout(() => {
        //       this.data.equation = '0';
        //       this.data.isMessage = false;
        //       this.setData({
        //         equation: this.data.equation,
        //         isMessage: this.data.isMessage,
        //       });
        //     }, 2000); //3s后执行清空操作
        //   }
        // }
        // this.data.count++; //点击一次等号计数器加1
        // if (this.data.count >= 10) {
        //   //当计数器大于等于10的时候置为0
        //   this.data.count = 0;
        //   this.setData({
        //     count: this.data.count
        //   })
        // }
        this.setData({
          equation: this.data.equation,
          // count: this.data.count,
          isMessage: this.data.isMessage,
          history: this.data.history,
          // emptyTips:this.data.emptyTips,
        });
      }
    }
    this.showResult();
    this.data.isClickCalculate = true;
    this.data.isDecimalAdded = false;
    this.data.isOperatorAdded = false;
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动 
    this.setData({
      equation: this.data.equation,
      isOperatorAdded: this.data.isOperatorAdded,
      isDecimalAdded: this.data.isDecimalAdded,
      isClickCalculate: this.data.isClickCalculate,
      history: this.data.history,
    });

  },
  //获取input框值时
  inputValue: function (e) {
    // console.log(e, "========");
    this.data.equation = e.detail.value; //赋值
  },
  //提交按钮
  enterInputValue: function () {
    this.calculate();
  },

  //点击正负号的时候
  calculateToggle: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/click.mp3";
    }
    if (this.data.isOperatorAdded || !this.data.isStarted) {
      return;
    }
    this.data.equation = this.data.equation + '* -1';
    this.calculate();
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    this.setData({
      equation: this.data.equation
    })

  },

  //点击百分号的时候
  calculatePercentage: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/click.mp3";
    }
    if (this.data.isOperatorAdded || !this.data.isStarted) {
      return;
    }
    this.data.equation = this.data.equation + '* 0.01';
    this.calculate();
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    this.setData({
      equation: this.data.equation
    });

  },

  //点击平方的时候
  square: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/click.mp3";
    }
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    //创建函数数组判断函数
    Array.prototype.in_array = function (element) {
      for (var i = 0; i < this[0].length; i++) {
        if (this[0][i] == element) {
          return true;
        }
      }
      return false;
    }
    this.data.emptyTips = '';
    this.setData({
      emptyTips: this.data.emptyTips
    });
    var arry = new Array(['+', '-', '×', '÷']); //创建用于判断加减乘除的数组
    for (var i = 0; i < this.data.equation.length; i++) {
      if (arry.in_array(this.data.equation[i])) {
        this.calculate();
      }
    }
    let history = this.data.equation + '×' + this.data.equation; //历史记录
    this.data.equation = this.data.equation * this.data.equation;
    let historyMessage = history + '=' + this.data.equation; //把历史记录赋值拼接
    this.historyText(historyMessage);
    this.showResult();
    this.setData({
      equation: this.data.equation,
      isSmall: this.data.isSmall,
      isTooSmall: this.data.isTooSmall,
      history: this.data.history,
    });
  },

  //点击清除符号的时候
  clear: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {

      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      bgm.src = "/pages/music/AllClear.mp3";
      // console.log(bgm); 
    }
    this.data.equation = '0';
    this.data.isDecimalAdded = false;
    this.data.isOperatorAdded = false;
    this.data.isStarted = false;
    this.data.isSmall = false;
    this.data.isTooSmall = false;
    this.data.isMessage = false;
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    this.setData({
      equation: this.data.equation,
      isOperatorAdded: this.data.isOperatorAdded,
      isDecimalAdded: this.data.isDecimalAdded,
      isSmall: this.data.isSmall,
      isTooSmall: this.data.isTooSmall,
      isStarted: this.data.isStarted,
      isMessage: this.data.isMessage,
    })
  },

  //点击退格键的时候
  oneClear: function (e) {
    //设置音效
    if (this.data.isMusicSwitch) {
      let bgm = wx.createInnerAudioContext();
      bgm.autoplay = true;
      bgm.loop = false;
      if (this.data.equation.length == 1 && this.data.equation != 0) {
        // console.log("剩下一个了");
        bgm.src = "/pages/music/AllClear.mp3";
      } else {
        bgm.src = "/pages/music/click.mp3";
      }

    }
    wx.vibrateShort({
      complete: (res) => {},
    }) //按键按下后震动
    var str = this.data.equation.toString();
    if (str.length == 1) {
      this.data.equation = "0";
      this.data.isStarted = false;
      this.data.isSmall = false;
      this.data.isTooSmall = false;
      this.data.isMessage = false;
      this.setData({
        equation: this.data.equation,
        isSmall: this.data.isSmall,
        isTooSmall: this.data.isTooSmall,
        isStarted: this.data.isStarted,
        isMessage: this.data.isMessage,
      });
    } else {
      this.data.equation = str.slice(0, str.length - 1);
      this.setData({
        equation: this.data.equation
      });
    }
    // this.data.isNightSwitch = !this.data.isNightSwitch;
    // this.setData({
    //   isNightSwitch:this.data.isNightSwitch,
    // })
  },

  //当结果框的显示问题
  showResult: function (e) {
    var that = this;
    //当输入内容宽度大于实际输入框宽度的时候，字体缩小适应输入框要求
    if (this.data.equation.toString().length > 11) {
      this.data.isSmall = true;
      if (this.data.equation.toString().length > 17) {
        this.data.isSmall = false;
        this.data.isTooSmall = true;
      }
    } else {
      this.data.isSmall = false;
      this.data.isTooSmall = false;
    }
    this.setData({
      isSmall: this.data.isSmall,
      isTooSmall: this.data.isTooSmall,
    })
  },

  //跳转页面到产品信息处
  tips: function (e) {
    wx.navigateTo({
      url: '/pages/introduce/introduce',
    })
  },
  //开关控制
  nightSwitch: function (e) {
    this.data.isNightSwitch = !this.data.isNightSwitch;
    // e.detail.value = this.data.isNightSwitch;
    this.night();
    this.setData({
      isNightSwitch: this.data.isNightSwitch,
    })
  },
  //封装夜间模式方法
  night: function () {
    // 把开关当前值传入内存
    wx.setStorageSync('nightOpen', this.data.isNightSwitch);
    // console.log( wx.getStorageSync('nightOpen'));
    //如果为夜间模式则状态栏变为黑暗模式
    if (this.data.isNightSwitch) {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#424242',
        animation: {
          duration: 200,
          timingFunc: 'easeIn'
        }
      })
    } else {
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#eee',
        animation: {
          duration: 0,
          timingFunc: 'easeIn'
        }
      })
    }
  },
  //封装自适应夜间模式方法
  autoNight: function () {
    var hours = new Date().getHours();
    if ((hours >= 20 && hours <= 23) || (hours >= 0 && hours <= 6)) {
      this.data.isNightSwitch = true;
      this.night();
    } else {
      this.data.isNightSwitch = false;
      this.night();
    }
    this.setData({
      isNightSwitch: this.data.isNightSwitch,
    })
  },
  //音效控制按钮
  musicSwitch: function (e) {
    this.data.isMusicSwitch = !this.data.isMusicSwitch;
    this.setData({
      isMusicSwitch: this.data.isMusicSwitch,
    })
  },
  //历史记录控制
  downHistory: function () {
    this.data.isHistory = !this.data.isHistory;
    if (this.data.isHistory) {
      this.data.downValue = "︽";
    } else {
      this.data.downValue = "︾";
    }
    this.setData({
      isHistory: this.data.isHistory,
      downValue: this.data.downValue,
    });
  },
  //历史记录加载到数组中
  historyText: function (historyMessage) {
    this.data.emptyTips = ''; //把当前提示文字置空
    const lastMessage = this.data.history[this.data.history.length - 1]; //获取前一个id的内容
    const messageId = lastMessage ? lastMessage.id + 1 : 1; //三元表达式创立新的记录id
    this.data.history.push({
      id: messageId,
      message: historyMessage,
      emptyTips: this.data.emptyTips,
    })
    var arr = this.data.history;
    var afterArr = []; //置空数组承接新数据
    //倒序显示结果
    for (var i = arr.length - 1; i >= 0; i--) {
      afterArr.push(arr[i]);
    }
    this.data.afterHistory = afterArr; //把新的数据复制给输出历史记录
    this.setData({
      afterHistory: this.data.afterHistory
    })
  },
  //点击历史记录反显到计算器上
  clickHistory: function (event) {
    // console.log(event.currentTarget.dataset.value);
    //截取等于号前面的字符
    this.data.equation = event.currentTarget.dataset.value.match(/(\S*)=/)[1];
    this.showResult();
    this.setData({
      equation: this.data.equation
    });
  },
  //清空历史记录
  clearHistory: function () {
    var that = this;
    wx.vibrateLong({
      complete: (res) => {},
    }) //按键按下后震动
    wx.showModal({
      cancelColor: '#c0392b',
      title: '清空提示',
      content: '你确定要清空计算历史记录吗？',
      cancelText: '取消',
      confirmText: '确认',
      confirmColor: '#16a085',
      success(res) {
        if (res.confirm) {
          that.data.history = [];
          that.data.afterHistory = [];
          that.data.emptyTips = '暂无计算记录';
          that.setData({
            history: that.data.history,
            afterHistory: that.data.afterHistory,
            emptyTips: that.data.emptyTips,
          });

        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.autoNight();
  },
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    //设置定时器一个小时监听一次页面
    var setTime = setInterval(() => {
      this.autoNight();
    }, 5400000);
    if (!showed) {
      showed = true;
      wx.showModal({
        title: '版本更新内容',
        content: 'v3版本更新:\r\n更新计算算法',
        showCancel: false, //不显示取消按钮
        confirmText: '知道了', //替换true false按键
        confirmColor: '#16a085'
      })
    }
  },

})